const path = require('path')
const fs = require('fs')
const ejs = require('ejs');

//编译ejs模版
const compile = (template, data) => {
  const templatePosition = `../templates/${template}`;
  const templatePath = path.resolve(__dirname, templatePosition);
  return new Promise((resolve, reject) => {
    ejs.renderFile(templatePath, { data }, {}, function (err, str) {
      if (err) {
        reject(err);
        return;
      }
      resolve(str)
    });
  })
}

//判断文件夹是否存在 不存在创建
const createDirSync = (pathName) => {
  if (fs.existsSync(pathName)) return true;
  //path.dirname(path)获取c的父路径 a/b/c 
  if (createDirSync(path.dirname(pathName))) {
    fs.mkdirSync(pathName);
    return true;
  }
}

//写到对应文件夹
const writeToFile = (path, content) => {
  //判断文件夹是否存在 不存在创建
  return fs.promises.writeFile(path, content)//返回promise

}

module.exports = {
  compile,
  writeToFile,
  createDirSync
}